import { dialog, Menu, Tray, shell, BrowserWindow, app } from 'electron';
import path from 'path';
import { version } from '@shared/constans/version';
import os from 'os';
import commonConst from "@shared/utils/platform"


function createTray(window: BrowserWindow, callback: (status: boolean) => void): Promise<Tray> {

    return new Promise((resolve) => {
      let icon;
      const appPath = app.getAppPath();
      if (commonConst.macOS()) {
        icon = 'icons/iconTemplate@2x.png';
      } else if (commonConst.windows()) {
        icon =
          parseInt(os.release()) < 10
            ? 'icons/icon@2x.png'
            : 'icons/icon.ico';
      } else {
        icon = 'icons/icon@2x.png';
      }
      const appIcon = new Tray(path.join(appPath, "resources", icon));
      appIcon.setToolTip("Pipeline for animation and VFX");

      const createContextMenu = () =>
        Menu.buildFromTemplate([
            {
                label: '显示工作台',
                click() {
                  if (window.isVisible()) {
                    if (window.isMinimized()) {
                      window.restore();
                      window.focus();
                    } else {
                      window.focus();
                    }
                  } else {
                    window.show()
                  }
                },
            },
            {
                label: '启动器',
                click() {
                  window.show();
                },
            },
            { type: 'separator' },
          {
            label: '帮助文档',
            click: () => {
              process.nextTick(() => {
                shell.openExternal('https://www.baidu.com/');
              });
            },
          },
          {
            label: '意见反馈',
            click: () => {
              process.nextTick(() => {
                shell.openExternal('https://www.baidu.com/');
              });
            },
          },
          { type: 'separator' },
          {
            label: '关于',
            click() {
              dialog.showMessageBox(window, {
                title: 'Lazisoft',
                message: 'Pipeline for animation and VFX projects toolkit',
                detail: `Version: ${version}\nAuthor: zuokangbo`,
              });

            },
          },
          { label: '退出',
            click() {
              callback(true)
              app.quit();
          },
        },
        ]);
      appIcon.on('click', () => {
        appIcon.setContextMenu(createContextMenu());
        appIcon.popUpContextMenu();
      });
      appIcon.setContextMenu(createContextMenu());
  
      resolve(appIcon);
    });
  }
  
export default createTray;
